load('js/bankConfig.js');
load('js/keys_comm.js');
load('js/bank_data_handle.js')
load('js/biz_util.js')
load('js/regex_util.js')
function checkFetchResult() {
    var allData = context.get(ALL_DATA) != null ? context.get(ALL_DATA) : new ArrayList()

    if (!"v6".equals(context.get("version"))){
        var debitData = context.get(DEBIT_DATA)
        var creditData = context.get(CREDIT_DATA)
        if (debitData != null){
            logger.info("任务：【 {} 】抓取到【{}】张借记卡信息", context.get(LUA_TASK_KEY), debitData.size())
            allData.addAll(debitData)
        }
        if (creditData != null){
            logger.info("任务：【 {} 】抓取到【{}】张信用卡信息", context.get(LUA_TASK_KEY), creditData.size())
            allData.addAll(creditData)
        }
    } else {
        var creditCardSize = context.get(keys.CRED_CARD_SIZE) == null ? 0 : Integer.parseInt(context.get(keys.CRED_CARD_SIZE));
        logger.info("任务：【 {} 】抓取到【{}】张信用卡信息", context.get(LUA_TASK_KEY), creditCardSize)
        var debitCardSize = context.get(keys.DEBT_CARD_SIZE) == null ? 0 : Integer.parseInt(context.get(keys.DEBT_CARD_SIZE));
        logger.info("任务：【 {} 】抓取到【{}】张借记卡信息", context.get(LUA_TASK_KEY), debitCardSize)
    }
    if (allData.size() == 0) {
        throwBankExceptionByErrorCode(BACR_20306_30)
    }
    //处理结果集
    context.put(ALL_DATA, allData)
    handleResultByOpenTime();
    var result = handleBeforeSerialize(allData)
    storeDataToFile(context, result, "result.json")
    logger.info("任务：【 {} 】抓取结果已存储本地文件系统, 文件大小【{}】字节", context.get(LUA_TASK_KEY), result.length())
    context.put("resultJson", result)

    // 结果集字段是否合法校验
    var propertyPath = new ArrayList()
    for each( var creditCardAllData in allData){
        var factory = Validation.buildDefaultValidatorFactory()
        var validator = factory.getValidator()
        var set = validator.validate(creditCardAllData)
        for each(var constraintViolation in set){
            propertyPath.add("( " + constraintViolation.getPropertyPath().toString() + " = " + constraintViolation.getInvalidValue() + " )")
        }
    }

    if (propertyPath.size() > 0) {
        logger.error("任务：【 {} 】非法属性路径：【 {} 】", context.get(LUA_TASK_KEY), propertyPath)
        throwBankExceptionByErrorCode(BACR_20306_30)
    }
    context.put(ALL_DATA, allData)
}

function handleBeforeSerialize(allData) {

    var ValueFilterExtend = Java.extend(ValueFilter);
    var valueFilter = new ValueFilterExtend()
    {
        process : function (object, name, value) {

            if (value instanceof BigDecimal) {
                //logger.info("任务：【 {} 】当前属性【 {} = {} 】", context.get(LUA_TASK_KEY), name, value)
                //利息字段保留原来精度，不做四舍五入处理
                if (equals(name, "interest")) {
                    return value
                } else {
                    return value.setScale(2, BigDecimal.ROUND_HALF_UP)
                }
            } else {

                return value;
            }
        }
    }
    return JSON.toJSONString(allData, valueFilter, SerializerFeature.WriteMapNullValue);
}

/**
 * 处理最终结果集，将开卡日期之前的空表头删掉
 */
function handleResultByOpenTime() {
    var sdf = new SimpleDateFormat("yyyy-MM");
    var allData = context.get(ALL_DATA);
    if (allData.size() <= 0) {
        throwBankExceptionByErrorCode(BACR_20306_30)
    }

    //首先将billMonth为空的billdata对象删掉
    logger.info("任务：【 {} 】删除未使用的BillAllData,{}", context.get(LUA_TASK_KEY),allData.size())
    for (var i = 0; i < allData.size(); i++) {
        var creditAllData = allData.get(i);
        var bills = creditAllData.getBills();
        for (var j = 0; j < bills.size(); j++) {
            var billAllData = bills.get(j);
            if (billAllData.getBillMonth() == null) {
                bills.remove(billAllData);
                j = -1
            }
        }
        creditAllData.setBills(bills);
    }
    logger.info("任务：【 {} 】删除开卡日期之前的BillAllData", context.get(LUA_TASK_KEY))
    for (var i = 0; i < allData.size(); i++) {
        var creditAllData = allData.get(i);
        var openTime = creditAllData.getOpenTime();
        if (openTime != null) {
            openTime = sdf.format(openTime);
            var bills = creditAllData.getBills();
            for (var j = 0; j < bills.size(); j++) {
                var billAllData = bills.get(j);
                var billMonth = billAllData.getBillMonth();
                //如果开卡时间大于账单月
                if (billMonth != null && openTime != null && compireStrDate(openTime, billMonth)) {
                    bills.remove(billAllData);
                    j = -1;
                }
            }
        }
    }

    //删除没有卡号的creditCardAllData（一般测试会出现）
    logger.info("任务：【 {} 】删除未使用的creditCardAllData", context.get(LUA_TASK_KEY))
    for (var i = 0; i < allData.size(); i++) {
        var creditCardAllData = allData.get(i);
        if(StringUtils.isBlank(creditCardAllData.getFullCardNum()) && StringUtils.isBlank(creditCardAllData.getNameOnCard()) && creditCardAllData.getBills().size() <= 0){
            allData.remove(creditCardAllData);
            i = -1;
        }
    }
}

/**
 * js封装异常监控方法
 * @param context
 * @param e
 */
function statCaughtExceptionByJS(context, e) {
    if (context.get("is_test") == true) {
        throw new Exception("单元测试过程中解析异常【" + e.message + "】");
    } else {
        statCaughtException(context, e);
    }
}